package com.spzx.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.domain.ProductSpec;
import com.spzx.mapper.BrandMapper;
import com.spzx.mapper.ProductSpecMapper;
import com.spzx.service.CategoryService;
import com.spzx.service.ProductSpecService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service
public class ProductSpecServiceImpl extends ServiceImpl<ProductSpecMapper, ProductSpec> implements ProductSpecService {
    @Override
    public List<ProductSpec> listProductSpec(ProductSpec productSpec) {
        String specName = productSpec.getSpecName();
        Long categoryId = productSpec.getCategoryId();
        List<ProductSpec> list = this.list(Wrappers.lambdaQuery(ProductSpec.class)
                .eq(specName != null, ProductSpec::getSpecName, specName)
                .eq(categoryId != null, ProductSpec::getCategoryId, categoryId));
        list.forEach(productSpec1 -> {
            String nameById = categoryService.getNameById(productSpec1.getCategoryId());
            productSpec1.setCategoryName(nameById);
        });

        return list;
    }

    @Resource
    CategoryService categoryService;
    @Resource
    BrandMapper brandMapper;
    @Override
    public ProductSpec getDetails(Long id) {
        ProductSpec byId = this.getById(id);
        Long categoryId = byId.getCategoryId();
        List<Long> fatherIdList = categoryService.getFatherIdList(categoryId);
        byId.setCategoryIdList(fatherIdList);
        return byId;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveProductSpec(ProductSpec productSpec) {
        Long categoryId = productSpec.getCategoryId();
        long count = this.count(Wrappers.lambdaQuery(ProductSpec.class).eq(ProductSpec::getCategoryId, categoryId));
        if (count > 0) {
            throw new ServiceException("该分类下已经存在该商品规格");
        }
        return this.save(productSpec);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateProductSpec(ProductSpec productSpec) {
        Long categoryId = productSpec.getCategoryId();
        Long id = productSpec.getId();
        long count = this.count(Wrappers.lambdaQuery(ProductSpec.class).eq(ProductSpec::getCategoryId, categoryId));
        if (count > 1) {
            throw new ServiceException("该分类下已经存在该商品规格");
        }
        if (count == 1) {
            Long id1 = this.getOne(Wrappers.lambdaQuery(ProductSpec.class).eq(ProductSpec::getCategoryId, categoryId)).getId();
            if (id1 != id) {
                throw new ServiceException("该分类下已经存在该商品规格");
            }
        }
        return this.updateById(productSpec);
    }



}
